package com.usian.controller;

import com.usian.feign.CartFeign;
import com.usian.feign.OrderFeign;
import com.usian.pojo.OrderInfo;
import com.usian.pojo.TbItem;
import com.usian.pojo.TbOrder;
import com.usian.pojo.TbOrderShipping;
import com.usian.utils.Result;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/frontend/order")
public class OrderController {

    @Autowired
    private OrderFeign orderFeign;

    @Autowired
    private CartFeign cartFeign;




    /**
     * 去结算
     * @param userId
     * @param token
     * @param ids
     * @return
     */
    @RequestMapping("goSettlement")
    public Result goSettlement(@RequestParam String userId,@RequestParam String token,
                               @RequestParam String[] ids){
        /* 查询出购物车所有商品 */
        Map<String, TbItem> cartFromRedis = cartFeign.getCartFromRedis(userId);
        List<TbItem> list = new ArrayList<>();
        /* 根据ids获得去结算的商品 */
        for (String id : ids) {
            list.add(cartFromRedis.get(id));
        }
        if (list.size()>0){
            return Result.ok(list);
        }
        return Result.error("error");
    }

    /**
     * 创建订单
     */
    @RequestMapping("/insertOrder")
    public Result insertOrder(String orderItem, TbOrder tbOrder , TbOrderShipping
            tbOrderShipping) {
        //因为一个request中只包含一个request body. 所以feign不支持多个@RequestBody。
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderItem(orderItem);
        orderInfo.setTbOrder(tbOrder);
        orderInfo.setTbOrderShipping(tbOrderShipping);
        Long orderId = orderFeign.insertOrder(orderInfo);
        if (orderId != null) {
            //删除购物车
            return Result.ok(orderId);
        }
        return Result.error("error");
    }

}
